package sweet.helper

import java.util.regex._

object Regex{
  private val _patternCache = new scala.collection.mutable.HashMap[String, Pattern]
  def pattern(ps: String): Pattern = {
    _patternCache.get(ps) match {
      case Some(ptn) => ptn
      case None => {
        val ptn = Pattern.compile(ps)
        _patternCache += ps -> ptn
        ptn
      }
    }
  }
  def apply(ps: String): Regex = {
    new Regex(pattern(ps))
  }
  
  
  def findGroupsByDelimeters(s: String): List[String]
    = findGroupsByDelimeters(s, """${""", """}""")
  
  def findGroupsByDelimeters(s: String, leftSep: String, rightSep: String): List[String]
    = findGroupsByDelimeters(s, leftSep, rightSep, """\""")
  
  def findGroupsByDelimeters(s: String, leftSep: String, rightSep: String, escape: String): List[String] = {
    val names = new scala.collection.mutable.ListBuffer[String]
    val re = Regex("""(?<=^\s*|[^("""+escape+")])"+leftSep+"(.+?)"+rightSep)
    val m = re.matcher(s)
    while((m.find && m.groupCount >=1))
      names += m.group(1)
    names.readOnly
  }
  
  implicit def pattern2regex(pattern: Pattern) = new Regex(pattern)
}
class Regex(val pattern: Pattern) {
  
  def matcher(s: String) = pattern.matcher(s)
  
  def find(s: String) = matcher(s).find
  
  def findGroups(s: String): List[String] = {
    val groups = new scala.collection.mutable.ListBuffer[String]
    val m = pattern.matcher(s)
    while(m.find)
      if(m.groupCount>0)
        for(i<-0 to m.groupCount)
          groups += m.group(i)
      else
        throw new Exception("No group found.")
    groups.readOnly
  }
}
